<template>
    <div style="margin-left: 2%;margin-right: 2%;margin-top: 10px">
        <el-card>
            <span style="font-size: 13px">项目编号：{{formData.projectCode}}</span>
            <span style="font-size: 13px;margin-left: 3%">项目名称：{{formData.projectName}}</span>
            <span style="font-size: 13px;margin-left: 3%">项目预算：{{formData.budget}}</span>
            <span style="margin-left: 2px;font-size: 13px">元</span>
            <span style="font-size: 13px;margin-left: 3%">采购类别：
                  <span v-if="formData.purchaseCategoryId === 1">货物类</span>
                  <span v-else-if="formData.purchaseCategoryId === 2">服务类</span>
                  <span v-else-if="formData.purchaseCategoryId === 3">工程类</span>
            </span>
        </el-card>
        <el-tabs v-model="activeTab">
            <el-tab-pane label="采购清单" name="tab1" @tab-click="handleTabClick">
                <el-dialog
                        title="添加"
                        :visible.sync="manageAddDialog"
                        width="40%"
                        center>
                    <el-form ref="addDetail" :rules="rules" :model="addDetail" label-width="150px">
                        <el-form-item label="货物名称" prop="goodsName">
                            <el-input  v-model="addDetail.goodsName" placeholder="输入内容"></el-input>
                        </el-form-item>
                        <el-form-item label="单价" prop="price">
                            <el-input  v-model="addDetail.price" placeholder="输入内容" @input="checkInput(addDetail, 'price'), calculateAmount(addDetail)"></el-input>
                        </el-form-item>
                        <el-form-item label="数量" prop="num">
                            <el-input  v-model="addDetail.num" placeholder="输入内容" @input="checkInput(addDetail,'num'), calculateAmount(addDetail)"></el-input>
                        </el-form-item>
                        <el-form-item label="金额(元)" prop="summoney">
                            <el-input  v-model="addDetail.summoney"></el-input>
                        </el-form-item>
                        <el-form-item label="规格及技术要求" prop="modelType">
                            <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 10}" v-model="addDetail.modelType" placeholder="输入内容" @input="checkNegativeKeywords"></el-input>
                        </el-form-item>
                        <div class="error-message" :class="{ 'show': hasNegativeKeyword }">规格及技术要求包含资格条件负面清单关键词{{this.hasnegativewords}}，请修改。</div>
                    </el-form>
                    <div style="text-align: center">
                        <el-button @click="manageSubmitAdd" type="primary">确 定</el-button>
                        <el-button @click="manageCancelAdd" type="primary">取 消</el-button>
                    </div>
                </el-dialog>
                <el-dialog
                        title="修改"
                        :visible.sync="manageModifyDialog"
                        width="40%"
                        center>
                    <el-form ref="editDetail" :rules="rules" :model="editDetail" label-width="120px">
                        <el-form-item label="货物名称" prop="goodsName">
                            <el-input  v-model="editDetail.goodsName" placeholder="输入内容"></el-input>
                        </el-form-item>
                        <el-form-item label="单价" prop="price">
                            <el-input  v-model="editDetail.price" placeholder="输入内容" @input="checkInput(editDetail,'price'), calculateAmount(editDetail)"></el-input>
                        </el-form-item>
                        <el-form-item label="数量" prop="num">
                            <el-input  v-model="editDetail.num" placeholder="输入内容" @input="checkInput(editDetail,'num'), calculateAmount(editDetail)"></el-input>
                        </el-form-item>
                        <el-form-item label="金额(元)" prop="summoney">
                            <el-input  v-model="editDetail.summoney"></el-input>
                        </el-form-item>
                        <el-form-item label="规格及技术要求" prop="modelType">
                            <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 10}" v-model="editDetail.modelType" placeholder="输入内容" @input="checkNegativeKeywords"></el-input>
                        </el-form-item>
                        <div class="error-message" :class="{ 'show': hasNegativeKeyword }">内容包含负面词汇{{this.hasnegativewords}}，请修改。</div>
                    </el-form>
                    <div style="text-align: center">
                        <el-button @click="manageSubmitModify" type="primary">确 定</el-button>
                        <el-button @click="manageCancelModify" type="primary">取 消</el-button>
                    </div>
                </el-dialog>
                <div :class="{'move-out': activeTab === 'tab2', 'move-in': activeTab === 'tab1'}">
                    <div style="text-align: left;display: inline-block">
                        <el-button size="mini" type="primary" @click="goBack">返回</el-button>
                    </div>
                    <div style="float: right;display: inline-block">
                        <el-button size="mini" type="primary" v-if="this.QuaSubmitStatus!=='已提交'" @click="manageAddDialog = true">添加</el-button>
                    </div>

                    <div style="margin-top: 14px;margin-bottom: 10px">
                        <el-table
                                :data="purchaseTable"
                                border
                                style="width: 100%">
                            <el-table-column
                                    prop="goodsName"
                                    min-width="30px"
                                    label="货物名称"
                            >
                            </el-table-column>
                            <el-table-column
                                    prop="modelType"
                                    min-width="30px"
                                    label="规格及技术要求"
                            >
                                <template slot-scope="scope">
                                    <div class="ellipses-container" @click="contentDetail = true">{{ scope.row.modelType }}</div>
                                    <el-dialog
                                            title="规格及技术要求"
                                            :visible.sync="contentDetail"
                                            width="60%"
                                            center>
                                        {{ scope.row.modelType }}
                                    </el-dialog>
                                </template>
                            </el-table-column>
                            <el-table-column
                                    prop="price"
                                    min-width="30px"
                                    label="单价(元)"
                            >
                            </el-table-column>
                            <el-table-column
                                    prop="num"
                                    min-width="30px"
                                    label="数量"
                            >
                            </el-table-column>
                            <el-table-column
                                    prop="summoney"
                                    min-width="30px"
                                    label="金额(元)">
                            </el-table-column>
                            <el-table-column
                                    v-if="this.QuaSubmitStatus!=='已提交'"
                                    prop="controls"
                                    width="170px"
                                    label="操作"
                            >
                                <template slot-scope="{$index,row}">
                                    <i  title="修改" @click="handleModifyClick(row)" style="color: dodgerblue;margin-right: 10px;cursor: pointer">修改</i>
                                    <i  title="删除" @click="manageDel(row)" style="color: dodgerblue;margin-right: 10px;cursor: pointer">删除</i>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>

                    <div style="font-size: 15px;margin-top: 20px;">总金额：{{ TotalMoney ? TotalMoney + ' 元' : '0 元' }}</div>
                </div>

            </el-tab-pane>
            <el-tab-pane label="供应商资格条件" name="tab2">
                <div :class="{'move-out': activeTab === 'tab1','move-in': activeTab === 'tab2'}">
                    <el-card ref="approveData" :model="approveData">
                        <div style="margin-top: 15px;font-size: 13px;display: inline-block;vertical-align: top;width: 150px;text-align:right">供应商资格条件：</div>
                        <div style="font-size: 13px;margin-top: 15px;display: inline-block">
                            <el-input v-model="approveData.quacondition" placeholder="输入内容" style="width: 540px" type="textarea" :rows="6"></el-input>
                        </div>
                        <br>
                        <div style="margin-top: 30px;font-size: 13px;display: inline-block;vertical-align: top;width: 150px;text-align:right">服务项目主要内容：</div>
                        <div style="font-size: 13px;margin-top: 30px;display: inline-block">
                            <el-input v-model="approveData.serviceProjectContent" placeholder="输入内容" style="width: 540px" type="textarea" :rows="3"></el-input>
                        </div>
                        <br>
                        <div style="margin-top: 30px;font-size: 13px;display: inline-block;vertical-align: top;width: 150px;text-align:right">维保期限(年)：</div>
                        <div style="font-size: 13px;margin-top: 30px;display: inline-block">
                            <el-input v-model="approveData.maintenancePeriod" placeholder="输入内容" @input="checkInput(approveData,'maintenancePeriod')" style="width: 130px"></el-input>
                        </div>
                        <br>
                        <div style="margin-top: 30px;font-size: 13px;display: inline-block;vertical-align: top;width: 150px;text-align:right">交货(服务、建设)地点：</div>
                        <div style="display: inline-block;margin-top: 30px">
                            <el-input v-model="approveData.deliveryPlace" placeholder="输入内容" style="width: 540px"></el-input>
                        </div>
                        <br>
                        <div style="margin-top: 30px;font-size: 13px;display: inline-block;vertical-align: top;width: 150px;text-align:right">交货(服务、建设)时间：</div>
                        <div style="display: inline-block;margin-top: 30px">
                            <el-input v-model="approveData.deliveryTime" style="width: 540px;white-space: pre-wrap" ></el-input>
                        </div>
                        <br>
                        <div style="margin-top: 30px;font-size: 13px;display: inline-block;vertical-align: top;width: 150px;text-align:right">付款方式：</div>
                        <div style="display: inline-block;margin-top: 30px">
                            <el-input v-model="approveData.payMethod" style="width: 540px;white-space: pre-wrap" type="textarea" :rows="3"></el-input>
                        </div>
                        <br>
                        <div style="margin-top: 30px;font-size: 13px;display: inline-block;vertical-align: top;width: 150px;text-align:right">项目售后：</div>
                        <div style="display: inline-block;margin-top: 30px">
                            <el-input v-model="approveData.projectAfterSale" placeholder="输入内容" style="width: 540px" type="textarea" :rows="3"></el-input>
                        </div>
                        <br>
                        <div style="margin-left: 80px;margin-top: 30px">
                            <span style="font-size: 13px;margin-left: 3%;width: 150px">提交状态：{{QuaSubmitStatus}}</span>
                            <span style="font-size: 13px;margin-left: 167px">提交时间：{{ QuaSubmitStatus ==='未提交'?"":QuaSubmitTime}}</span>
                        </div>
                        <div style="margin-left: 80px;margin-top: 30px">
                            <span style="font-size: 13px;margin-left: 3%;width: 150px">审批状态：{{QuaApproveStatus}}</span>
                            <span style="font-size: 13px;margin-left: 167px">审批时间：{{QuaApproveTime}}</span>
                        </div>
                        <div style="margin-left: 220px;margin-top: 30px;">
                    <span>
                      <el-button @click="approveSave" type="primary" v-if="this.QuaSubmitStatus!=='已提交'">保 存</el-button>
                    </span>
                            <span style="margin-left: 40px;">
                      <el-button @click="approveSubmit" type="primary" v-if="this.QuaSubmitStatus!=='已提交'">提交审批</el-button>
                    </span>
                            <span style="margin-left: 40px;">
                      <el-button @click="goBack" type="primary">返回</el-button>
                    </span>
                        </div>
                    </el-card>
                </div>
            </el-tab-pane>
        </el-tabs>
    </div>
</template>

<script>
    import {
        reqApproveCheck,
        reqApproveGet, reqApproveSave, reqApproveSubmit,
        reqManageAdd,
        reqManageDel,
        reqManageModify, reqNegativeKeywords,
        reqPurchaseList
    } from "@/api/purchaseItemManage";


    export default {
        name: "itemManage",
        data() {
            return {
                formData: {
                    projectId:'',
                    projectCode: '',
                    projectName: '',
                    purchaseCategoryId: '',
                    budget: '',
                },
                addDetail: {
                    goodsName:'',
                    modelType:'',
                    summoney:'',
                    num:'',
                    price:''
                },
                editDetail: {
                    goodsName:'',
                    modelType:'',
                    summoney:'',
                    num:'',
                    price:''
                },
                approveData: {
                    projectId: '',
                    quacondition: '',
                    serviceProjectContent: '',
                    projectDuration: '',
                    deliveryPlace:'',
                    deliveryTime: '',
                    maintenancePeriod:'',
                    projectAfterSale:'',
                    payMethod:'',
                },
                rules: {
                    goodsName: [{ required: true, message: '请输入货物名称', trigger: 'blur' }],
                    price: [{ required: true, message: '请输入单价', trigger: 'blur' }],
                    num: [{ required: true, message: '请输入数量', trigger: 'blur' }],
                    summoney: [{ required: true, message: '请输入金额', trigger: 'blur' }],
                    modelType: [{ required: true, message: '请输入规格及技术要求', trigger: 'blur' }],
                    quacondition: [{ required: true, message: '请输入供应商资格条件', trigger: 'blur' }],
                    serviceProjectContent: [{ required: true, message: '请输入服务项目主要内容', trigger: 'blur' }],
                    maintenancePeriod: [{ required: true, message: '请输入维保期限', trigger: 'blur' }],
                    deliveryPlace: [{ required: true, message: '请输入交货(服务、建设)地点', trigger: 'blur' }],
                    deliveryTime: [{ required: true, message: '请输入交货(服务、建设)时间', trigger: 'blur' }],
                    payMethod: [{ required: true, message: '请输入付款方式', trigger: 'blur' }],
                    projectAfterSale: [{ required: true, message: '请输入项目售后', trigger: 'blur' }]
                },
                purchaseTable:[],
                manageAddDialog: false,
                manageModifyDialog: false,
                negativekeywords: [],
                hasnegativewords:[],
                hasNegativeKeyword: false,
                contentDetail: false,
                total: 0,
                TotalMoney: '',
                QuaSubmitStatus:'',
                QuaSubmitTime:'',
                QuaApproveStatus:'',
                QuaApproveTime:'',
                activeTab: 'tab1',

            }
        },
        created() {
            // 接收路由传递的数据
            this.formData.projectId = this.$route.params.projectId;
            this.formData.projectCode = this.$route.params.projectCode;
            this.formData.projectName = this.$route.params.projectName;
            this.formData.purchaseCategoryId = this.$route.params.purchaseCategoryId;
            this.formData.budget = this.$route.params.budget;

            this.getPurchaseList(this.formData.projectId)
            this.approveGet()
            this.getNegativeKeywords();
        },
        methods: {
            //切换选项卡
            handleTabClick(tab) {
                this.activeTab = tab.name;
            },

            //获取项目采购清单
            async getPurchaseList(projectId){
                let res =await reqPurchaseList(projectId)
                if(res.data.code===200){
                    this.purchaseTable=res.data.data.records;
                    this.TotalMoney=res.data.data.totalMoney;
                    this.total = res.data.data.total;
                }
            },

            //单价、数量、金额、维保期限禁止输入非数字
            checkInput(object, field) {
                const value = object[field];
                if (isNaN(value)) {
                    this.showInputError();
                    object[field] = '';
                }
            },
            showInputError() {
                this.$message({
                    message: '请输入数字',
                    type: 'warning',
                });
            },

            //金额自动计算
            calculateAmount(dataObject) {
                const price = parseFloat(dataObject.price);
                const num = parseInt(dataObject.num);
                if (!isNaN(price) && !isNaN(num)) {
                    dataObject.summoney = price * num;
                } else {
                    dataObject.summoney = '';
                }
            },

            //购物清单添加
            async manageSubmitAdd() {
                this.$refs.addDetail.validate(async (valid) => {
                    if (valid) {
                        const inputObj = {
                            projectId: this.formData.projectId,
                            goodsName: this.addDetail.goodsName,
                            price: this.addDetail.price,
                            num: this.addDetail.num,
                            summoney: this.addDetail.summoney,
                            modelType: this.addDetail.modelType,
                        };
                        let res =await reqManageAdd(inputObj)
                        if(res.data.code===200){
                            this.$message({
                                type: 'success',
                                message: '添加成功!'
                            });
                            this.addDetail = {
                                goodsName: '',
                                price: '',
                                num: '',
                                summoney: '',
                                modelType: '',
                            };
                            this.$refs["addDetail"].resetFields();
                            this.manageAddDialog = false;
                            await this.getPurchaseList(this.formData.projectId)
                        }else if (res.data.code === 456) {
                            this.$message({
                                type: 'error',
                                message: res.data.msg
                            })
                            this.openImgDialog()
                        }else {
                            this.$message.error(res.data.msg);
                        }
                    }
                })
            },

            //购物清单取消添加
            manageCancelAdd() {
                this.addDetail = {
                    goodsName: '',
                    price: '',
                    num: '',
                    summoney: '',
                    modelType: '',
                };
                this.$refs["addDetail"].resetFields();
                this.manageAddDialog = false;
            },

            //打开采购清单修改弹窗
            handleModifyClick(row) {
                this.editDetail = {
                    id: row.id,
                    goodsName: row.goodsName,
                    price: row.price,
                    num: row.num,
                    summoney: row.summoney,
                    modelType: row.modelType,
                };
                this.manageModifyDialog = true;
            },

            //购物清单修改
            async manageSubmitModify() {
                this.$refs.editDetail.validate(async (valid) => {
                    if (valid) {
                        const inputObj = {
                            id:this.editDetail.id,
                            projectId: this.formData.projectId,
                            goodsName: this.editDetail.goodsName,
                            price: this.editDetail.price,
                            num: this.editDetail.num,
                            summoney: this.editDetail.summoney,
                            modelType: this.editDetail.modelType,
                        };
                        let res =await reqManageModify(inputObj)
                        if(res.data.code===200){
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                        }else {
                            this.$message.error(res.data.msg);
                        }
                        this.editDetail = {
                            id:'',
                            goodsName: '',
                            price: '',
                            num: '',
                            summoney: '',
                            modelType: '',
                        };
                        this.$refs["editDetail"].resetFields();
                        this.manageModifyDialog = false;
                        await this.getPurchaseList(this.formData.projectId)
                    }
                })
            },

            //购物清单取消修改
            manageCancelModify() {
                this.editDetail = {
                    id:'',
                    goodsName: '',
                    price: '',
                    num: '',
                    summoney: '',
                    modelType: '',
                };
                this.$refs["editDetail"].resetFields();
                this.manageModifyDialog = false;
            },


            //购物清单删除
            async manageDel(row) {
                this.$confirm('确认删除这条采购清单吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(async () => {
                    let res = await reqManageDel(row.id)
                    if (res.data.code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        await this.getPurchaseList(this.formData.projectId)
                    } else {
                        this.$message.error(res.data.msg)
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },

            //获取提交审批数据
            async approveGet() {
                let res = await reqApproveGet(this.formData.projectId)

                if(res.data.code===200){
                    this.approveData = res.data.data
                    if(res.data.data.deliveryTime == null){
                        this.approveData.deliveryTime = "合同签订之日起90日内完成项目并且通过验收"
                    }
                    if(res.data.data.payMethod == null){
                        this.approveData.payMethod = "签订合同后支付合同总价款40%作为预付款，项目完成后支付合同总价款40%，验收合格后，凭《验收资料》支付合同总价款的20%"
                    }
                    this.QuaSubmitStatus = res.data.data.quaSubmitStatus
                    this.QuaApproveStatus = res.data.data.quaApproveStatus
                    this.QuaSubmitTime = res.data.data.quaSubmitTime
                    this.QuaApproveTime = res.data.data.quaApproveTime
                }else {
                    this.$message.error(res.data.msg);
                }
            },

            //保存
            async approveSave() {
                const inputObj = {
                    projectId: this.formData.projectId,
                    quacondition: this.approveData.quacondition,
                    serviceProjectContent: this.approveData.serviceProjectContent,
                    projectDuration : this.approveData.projectDuration,
                    deliveryPlace: this.approveData.deliveryPlace ,
                    deliveryTime: this.approveData.deliveryTime,
                    maintenancePeriod: this.approveData.maintenancePeriod,
                    payMethod: this.approveData.payMethod,
                    projectAfterSale: this.approveData.projectAfterSale
                };
                let ress = await reqApproveCheck(inputObj)
                if(ress.data.code===200){
                    let res =await reqApproveSave(inputObj)
                    if(res.data.code===200){
                        this.$message({
                            type: 'success',
                            message: '保存成功!'
                        });
                    }else {
                        this.$message.error(res.data.msg);
                    }
                }else {
                    this.$message.error(ress.data.msg);
                }
            },

            //提交审批
            async approveSubmit() {
                const inputObj = {
                    projectId: this.formData.projectId,
                    quacondition: this.approveData.quacondition,
                    serviceProjectContent: this.approveData.serviceProjectContent,
                    deliveryPlace: this.approveData.deliveryPlace ,
                    deliveryTime: this.approveData.deliveryTime,
                    maintenancePeriod: this.approveData.maintenancePeriod,
                    payMethod: this.approveData.payMethod,
                    projectAfterSale: this.approveData.projectAfterSale
                };
                console.log(inputObj)
                if (this.approveData.quacondition==null||this.approveData.serviceProjectContent==null||this.approveData.deliveryPlace==null||this.approveData.maintenancePeriod==null||this.approveData.projectAfterSale==null) {
                    this.$message({
                        type: 'warning',
                        message: '请确保所有信息填写完整!'
                    });
                    return;
                } else if (this.approveData.quacondition===""||this.approveData.serviceProjectContent===""||this.approveData.deliveryPlace===""||this.approveData.maintenancePeriod===""||this.approveData.projectAfterSale==="") {
                    this.$message({
                        type: 'warning',
                        message: '请确保所有信息填写完整!'
                    });
                    return;
                }
                let ress = await reqApproveCheck(inputObj)
                if (ress.data.code === 200) {
                    this.$confirm('确定提交审批吗?', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(async () => {
                        let res = await reqApproveSubmit(inputObj)
                        if (res.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '提交成功!'
                            })
                            await this.approveGet()
                        } else {
                            this.$message.error(res.data.msg);
                        }
                        await this.approveGet()
                    })
                } else {
                    this.$message.error(ress.data.msg);
                }
            },

            //检查有无负面关键词
            async getNegativeKeywords() {
                try {
                    const response = await reqNegativeKeywords();
                    this.negativekeywords = response.data;
                } catch (error) {
                    console.error('请求负面关键词列表失败:', error);
                }
            },
            checkNegativeKeywords() {
                const inputText = this.addDetail.modelType.toLowerCase();
                const containsNegativeKeyword = this.negativekeywords.some(keyword =>
                    inputText.includes(keyword.toLowerCase())
                );
                this.hasNegativeKeyword = containsNegativeKeyword;
                if (containsNegativeKeyword) {
                    // 如果检测到负面关键词，将所有关键词添加到hasnegativewords数组中
                    this.hasnegativewords = this.negativekeywords.filter(keyword =>
                        inputText.includes(keyword.toLowerCase())
                    );
                } else {
                    // 如果没有检测到负面关键词，将hasnegativewords数组清空
                    this.hasnegativewords = [];
                }
            },

            //返回
            goBack() {
                this.$router.push('purchaseItemManage');
            },
        }
    }
</script>

<style scoped>
    .move-out {
        animation: moveOut 1s forwards;
    }

    .move-in {
        animation: moveIn 1s forwards;
    }

    .error-message {
        color: red;
        font-size: 12px;
        margin-top: 5px;
        display: none;
    }

    .error-message.show {
        display: block;
    }

    .ellipses-container {
        width: 150px; /* 设置容器宽度 */
        white-space: nowrap; /* 防止内容换行 */
        overflow: hidden; /* 隐藏超出容器宽度的部分 */
        text-overflow: ellipsis; /* 超出容器宽度时显示省略号 */
        cursor: pointer;
    }

</style>
